package com.example.common.exception;

import com.example.common.api.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<String> methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e) {
        return getVerificationFailedResult(e.getBindingResult().getFieldErrors());
    }

    @ExceptionHandler(value = BindException.class)
    public CommonResult<String> bindExceptionHandle(BindException e) {
        return getVerificationFailedResult(e.getFieldErrors());
    }

    @ExceptionHandler(BizException.class)
    public CommonResult<String> bizExceptionHandler(BizException e) {
        return CommonResult.failed(e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public CommonResult<String> illegalArgumentExceptionHandler(IllegalArgumentException e) {
        return CommonResult.validateFailed(e.getMessage());
    }

    private static CommonResult<String> getVerificationFailedResult(List<FieldError> fieldErrors) {
        String message = fieldErrors.stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return CommonResult.validateFailed(message);
    }
}